

import 'dart:io';

import 'package:xsdk_flutter/xsdk/framework/bean/x_bean_device.dart';
import 'package:xsdk_flutter/xsdk/operation/x_constant_temp.dart';
import 'package:xsdk_flutter/xsdk/utils/queue/x_bean_queue_message.dart';
import 'package:xsdk_flutter/xsdk/utils/queue/x_queue.dart';
import 'package:xsdk_flutter/xsdk/utils/socket/base/x_socket_client.dart';
import 'package:xsdk_flutter/xsdk/utils/socket/base/x_socket_server.dart';
import 'package:xsdk_flutter/xsdk/utils/socket/support/x_socket_notify_callback.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_date.dart';
import 'package:xsdk_flutter/xsdk/utils/json/x_utils_json.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_log.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_share_preferences.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_string.dart';

/*
socket通信,支持android,iOS,windows,mac
普通socket服务端/客户端, 注意: 同一个设备,只能有一个服务端socket
socket网络打印机(IP), 注意: 添加时设置属性为短连接

 */
abstract class XSocketUtils{

  static XServerSocketAPI? serverSocketAPI;

  //客户端(长连接)
  static final List<XClientSocketLongConnectAPI> _listClientSocketLongConnectAPI=[];
  //客户端(短连接)
  static final List<XClientSocketShortConnectAPI> _listClientSocketShortConnectAPI=[];

  //连接设备
  static final Set<XBaseDevice> socketDeviceList={};

  //消息队列
  static XQueue? _queue;

  /*
  1.初始化 ok(注意:不能在app中初始化,因为sp初始化没完成,导致获取设备记录为空)
  注意:
  1.1.如果使用多用户保存:
  则需要登录后更新用户组:XSharePreferencesUtils.saveString(XConstants.SP_UserGroup,XXX);
  然后再初始化;切换用户或company时,则需要重新初始化
  1.2.如果不启用多用户,则可在欢迎界面初始化;
   */
  static void init(){

    //断开所有连接(用于重新初始化)
    if(serverSocketAPI!=null){
      serverSocketAPI!.xRelease();
      serverSocketAPI=null;
    }

    //
    for(XClientSocketLongConnectAPI clientSocketAPI in _listClientSocketLongConnectAPI){
      clientSocketAPI.xRelease();
    }
    _listClientSocketLongConnectAPI.clear();

    socketDeviceList.clear();

    //1.连接设备
    String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
    String connectDeviceJson=XSharePreferencesUtils.getString('$userGroup${XConstants.SP_SocketDevicesList}');

    if(!XStringUtils.isEmpty(connectDeviceJson)){
      List<dynamic> list=XJsonUtils.json2List(connectDeviceJson);
      for(dynamic item in list){
        XBaseDevice baseDevice=XBaseDevice.fromJson(item);
        baseDevice.isConnected=false;
        socketDeviceList.add(baseDevice);
        //连接
        _connectDevice(baseDevice);
      }
    }

    XLogUtils.printLog('---设备socket记录数=${socketDeviceList.length}');

    //3.启动消息队列
    _queue??=XQueue(
        queueName: 'XSocketUtilsQueue',
        isEnableHeartBeat:true, //启动心跳包(用于定期检查清除过期短连接)
        heartbeatTime: 10,
        isConcurrentMode:true, //这里要设置并发(不按顺序,否则打印失败,这重新打印再次卡住不能往下打印)
        notifyHandleMsg: (XBaseQueueMessage msg) async {
          //接收到队列消息通知,取出消息并写入蓝牙设备(这里不需要再开线程,已在线程内) ok
          try{

            if(msg.isHeartbeatCommand){
              //服务端,客户端发送心跳包
              //XLogUtils.printLog('---服务端,客户端发送心跳包');

              if(serverSocketAPI!=null){
                serverSocketAPI!.sendAllClientSocketMessage(msg);
              }

              //长连接,适配socket网络打印机,避免打印心跳包字符串
              for(XClientSocketLongConnectAPI clientSocketAPI in _listClientSocketLongConnectAPI){
                //XLogUtils.printLog('---客户端发送心跳包:${clientSocketAPI.device.ip}');
                clientSocketAPI.sendMessage(msg);
              }

              _handleWriteSocketDeviceSucceed(isServer:msg.isServerSendToClientMessage,isCustomSocketCommunication:false,ip:msg.ip??'',msg:msg);

            }else{
              //发送内容
              if(msg.isServerSendToClientMessage){
                //服务端发送客户端
                if(serverSocketAPI!=null){
                  try{
                    bool isSuccess= serverSocketAPI!.sendMessage(msg.ip,msg.port,msg);
                    if(isSuccess){
                      _handleWriteSocketDeviceSucceed(isServer:true,isCustomSocketCommunication:true,ip:msg.ip??'',msg:msg);
                    }else{
                      _handleWriteSocketDeviceFailed(isServer:true,ip:msg.ip??'',errorLog:"Socket设备写入发生出错",msg:msg);
                    }
                    return;
                  }catch(e){
                    //
                  }
                }
              }else{
                //客户端发送到服务端

                //1.以指定ip为优先(只有1台设备打印,或自定义socket通信)
                if (!XStringUtils.isEmpty(msg.ip)){

                  //客户端(长连接)
                  for(XClientSocketLongConnectAPI clientSocketAPI in _listClientSocketLongConnectAPI){
                    try{
                      if(clientSocketAPI.serverIP==msg.ip && clientSocketAPI.serverPort==msg.port){
                        bool isSuccess= clientSocketAPI.sendMessage(msg);
                        XLogUtils.printLog('---socket通讯以指定ip为优先,isSuccess=$isSuccess');

                        if(isSuccess){
                          _handleWriteSocketDeviceSucceed(isServer:msg.isServerSendToClientMessage,isCustomSocketCommunication:clientSocketAPI.isCustomSocketCommunication,ip:msg.ip??'',msg:msg);
                        }else{
                          _handleWriteSocketDeviceFailed(isServer:msg.isServerSendToClientMessage,ip:msg.ip??'',errorLog:"Socket设备写入发生出错",msg:msg);
                        }
                        return;
                      }

                    }catch(e){
                      XLogUtils.printLog('---socket通讯以指定ip为优先,长连接,err: $e');
                    }
                  }

                  //短连接
                  bool isSucceedSend=false;
                  for(XClientSocketShortConnectAPI shortConnectApi in _listClientSocketShortConnectAPI){
                    try{
                      if(shortConnectApi.serverIP==msg.ip && shortConnectApi.serverPort==msg.port){
                        //
                        XLogUtils.printLog('---存在延迟客户端socket短连接');
                        isSucceedSend= shortConnectApi.sendMessage(msg);
                        if(isSucceedSend){
                          //成功
                          shortConnectApi.createTime=XDateUtils.getCurrentTime_ms();
                          _handleWriteSocketDeviceSucceed(isServer:msg.isServerSendToClientMessage,isCustomSocketCommunication:shortConnectApi.isCustomSocketCommunication,ip:msg.ip??'',msg:msg);
                          return;
                        }else{
                          //失败
                          shortConnectApi.xRelease();
                          _listClientSocketShortConnectAPI.remove(shortConnectApi);
                          XLogUtils.printLog('---延迟客户端socket短连接写入失败,删除延迟连接');
                        }
                        break;
                      }
                    }catch(e){
                      //
                    }
                  }

                  if(!isSucceedSend){
                    XLogUtils.printLog('---创建新客户端socket短连接');

                    for(XBaseDevice device in socketDeviceList){

                      if(!device.isServerSocket && device.isSocketShortConnect && msg.ip==device.ip && device.port==msg.port){

                        try{
                          Socket.connect(msg.ip, msg.port,timeout: const Duration(seconds: 10)).then((Socket socket) {
                            XLogUtils.printLog('---socket客户端连接成功!');
                            device.isConnected=true;
                            XClientSocketShortConnectAPI shortConnectAPI=XClientSocketShortConnectAPI(socket,device);

                            isSucceedSend= shortConnectAPI.sendMessage(msg);

                            if(isSucceedSend){
                              _handleWriteSocketDeviceSucceed(isServer:msg.isServerSendToClientMessage,isCustomSocketCommunication:shortConnectAPI.isCustomSocketCommunication,ip:msg.ip??'',msg:msg);
                              _listClientSocketShortConnectAPI.add(shortConnectAPI);
                            }else{
                              _handleWriteSocketDeviceFailed(isServer:msg.isServerSendToClientMessage,ip:msg.ip??'',errorLog:"Socket设备写入发生出错",msg:msg);
                            }

                          }).onError((error, stackTrace){
                            _handleWriteSocketDeviceFailed(isServer:msg.isServerSendToClientMessage,ip:msg.ip??'',errorLog:"客户端socket短连接失败",msg:msg);
                          });

                        }catch(e){
                          _handleWriteSocketDeviceFailed(isServer:msg.isServerSendToClientMessage,ip:msg.ip??'',errorLog:"客户端socket短连接失败",msg:msg);
                        }

                        return;
                      }
                    }

                  }

                  //不存指定socket设备
                  _handleWriteSocketDeviceFailed(isServer:msg.isServerSendToClientMessage,ip:msg.ip!,errorLog:"不存在socket设备",msg:msg);

                }else if(msg.deviceScene!=null){
                  XLogUtils.printLog('---socket通讯指定场景');
                  //2.指定场景,获得对应对应的设备(可能有多个),内部网络打印机等

                  //消息中是否有设备序号
                  String? serialNumber=msg.deviceSerialNumber;

                  //是否打印成功
                  bool isSucceedSend=false;

                  //长连接(对应一台设备)
                  for(XClientSocketLongConnectAPI clientSocketAPI in _listClientSocketLongConnectAPI){
                    try{
                      XBaseDevice baseDevice=clientSocketAPI.device;
                      List<XBaseDeviceScene>? scenes=baseDevice.scenes;
                      if(scenes!=null && scenes.isNotEmpty){
                        for(XBaseDeviceScene itemScene in scenes){
                          if(msg.deviceScene==itemScene){
                            //
                            if(!XStringUtils.isEmpty(serialNumber)){
                              //消息存在指定设备序号,再以场景+序号判断
                              if(serialNumber==baseDevice.serialNumber){
                                //写入数据
                                isSucceedSend= clientSocketAPI.sendMessage(msg);

                                if(isSucceedSend){
                                  _handleWriteSocketDeviceSucceed(isServer:msg.isServerSendToClientMessage,isCustomSocketCommunication:clientSocketAPI.isCustomSocketCommunication,ip:baseDevice.ip??'',msg:msg);
                                }else{
                                  _handleWriteSocketDeviceFailed(isServer:msg.isServerSendToClientMessage,ip:baseDevice.ip??'',errorLog:"Socket设备写入发生出错",msg:msg);
                                }

                                return;
                              }
                            }else{
                              //消息的场景没有指定设备序号,即以场景判断即可
                              //写入数据
                              isSucceedSend= clientSocketAPI.sendMessage(msg);

                              if(isSucceedSend){
                                _handleWriteSocketDeviceSucceed(isServer:msg.isServerSendToClientMessage,isCustomSocketCommunication:clientSocketAPI.isCustomSocketCommunication,ip:baseDevice.ip??'',msg:msg);
                              }else{
                                _handleWriteSocketDeviceFailed(isServer:msg.isServerSendToClientMessage,ip:baseDevice.ip??'',errorLog:"Socket设备写入发生出错",msg:msg);
                              }

                              return;
                            }
                          }
                        }
                      }
                    }catch(e){
                      //
                    }
                  }

                  //短连接(对应一台设备)
                  for(XBaseDevice device in socketDeviceList){
                    try{
                      if(!device.isServerSocket && device.isSocketShortConnect){
                        List<XBaseDeviceScene>? scenes=device.scenes;
                        if(scenes!=null && scenes.isNotEmpty){
                          for(XBaseDeviceScene itemScene in scenes){
                            if(msg.deviceScene==itemScene){
                              //
                              if(!XStringUtils.isEmpty(serialNumber)){
                                //消息存在指定设备序号,再以场景+序号判断
                                if(serialNumber==device.serialNumber){
                                  //写入数据,在内部处理成功和失败
                                  await _useShortConnectClientSocketSendMessageForScene(device,msg);
                                  return;
                                }
                              }else{
                                //消息没有指定设备序号,即以场景判断即可
                                //写入数据,在内部处理成功和失败
                                await _useShortConnectClientSocketSendMessageForScene(device,msg);
                                return;
                              }
                            }
                          }
                        }
                      }
                    }catch(e){
                      //
                    }
                  }

                  //不存指定socket设备
                  _handleWriteSocketDeviceFailed(isServer:msg.isServerSendToClientMessage,ip:msg.ip!,errorLog:"不存在socket设备",msg:msg);

                }
              }
            }

          }catch(e){
            XLogUtils.printLog('---socket设备写入出错,isServerSendToClientMessage= ${msg.isServerSendToClientMessage},${msg.ip}, $e');
            //处理写入消息失败
            _handleWriteSocketDeviceFailed(isServer:msg.isServerSendToClientMessage,ip:msg.ip!,errorLog:"socket设备写入发生出错",msg:msg);
          }
        },
        notifyTempMsgQueueIdleAndMsgQueueHasItem: () {
          //...
          //XLogUtils.printLog('---socket notifyTempMsgQueueIdleAndMsgQueueHasItem');
        },
        notifyHandleHeartbeat: () {
          //接收到心跳包通知 ok
          XLogUtils.printLog('---XSocketUtils,间隔${_queue?.heartbeatTime}秒收到处理XQueue心跳包',tag: 'XOther');

          //检测短连接过期时间
          _listClientSocketShortConnectAPI.removeWhere((XClientSocketShortConnectAPI shortConnectAPI){
            if(shortConnectAPI.socket==null){
              XLogUtils.printLog('---心跳自动清除短连接,socket=null');
              return true;
            }
            //超过10秒断开连接
            int nowTime=XDateUtils.getCurrentTime_ms();
            if(nowTime-shortConnectAPI.createTime>10*1000){
              XLogUtils.printLog('---心跳自动清除短连接,10秒');
              shortConnectAPI.xRelease();
              return true;
            }

            return false;
          });


          //自动发送自定义心跳包(可以检测长连接是否断链)
          if(_listClientSocketLongConnectAPI.isNotEmpty || (serverSocketAPI!=null && serverSocketAPI!.clientSockets.isNotEmpty)){
            //心跳包命令
            XBaseQueueMessage _heartbeatMsg=XBaseQueueMessage(
              msgId: 'heartbeat_${XDateUtils.getCurrentTime_ms()}',
              isPriorityHandle: true,
              isHeartbeatCommand: true,
            );
            sendMsgToQueue(_heartbeatMsg);
          }
        }
    );

    //初始化队列
    _queue?.init();

  }



  //短连接客户端打印,按场景 (对应一台设备)
  static Future<void> _useShortConnectClientSocketSendMessageForScene(XBaseDevice device,XBaseQueueMessage msg) async{
    bool isSucceedSend=false;

    //判断是否存在延迟关闭短连接...
    for(XClientSocketShortConnectAPI shortConnectApi in _listClientSocketShortConnectAPI){
      try{
        XBaseDevice baseDevice=shortConnectApi.device;
        if(baseDevice==device){
          //写入数据
          isSucceedSend= shortConnectApi.sendMessage(msg);
          if(isSucceedSend){
            //成功
            shortConnectApi.createTime=XDateUtils.getCurrentTime_ms();
            _handleWriteSocketDeviceSucceed(isServer:msg.isServerSendToClientMessage,isCustomSocketCommunication:shortConnectApi.isCustomSocketCommunication,ip:msg.ip??'',msg:msg);
            return;
          }else{
            //失败
            shortConnectApi.xRelease();
            _listClientSocketShortConnectAPI.remove(shortConnectApi);
            XLogUtils.printLog('---延迟客户端socket短连接写入失败,删除延迟连接');
          }
          break;
        }
      }catch(e){
        //
      }
    }

    if(!isSucceedSend){
      XLogUtils.printLog('---创建新客户端socket短连接');

      try{
        Socket.connect(device.ip, device.port,timeout: const Duration(seconds: 10)).then((Socket socket) {
          XLogUtils.printLog('---socket客户端连接成功!');
          device.isConnected=true;
          XClientSocketShortConnectAPI shortConnectAPI=XClientSocketShortConnectAPI(socket,device);

          isSucceedSend= shortConnectAPI.sendMessage(msg);

          if(isSucceedSend){
            _handleWriteSocketDeviceSucceed(isServer:msg.isServerSendToClientMessage,isCustomSocketCommunication:shortConnectAPI.isCustomSocketCommunication,ip:device.ip??'',msg:msg);
            _listClientSocketShortConnectAPI.add(shortConnectAPI);
          }else{
            _handleWriteSocketDeviceFailed(isServer:msg.isServerSendToClientMessage,ip:device.ip??'',errorLog:"Socket设备写入发生出错",msg:msg);
          }

        }).onError((error, stackTrace){
          _handleWriteSocketDeviceFailed(isServer:msg.isServerSendToClientMessage,ip:device.ip??'',errorLog:"客户端socket短连接失败",msg:msg);
        });

      }catch(e){
        _handleWriteSocketDeviceFailed(isServer:msg.isServerSendToClientMessage,ip:device.ip??'',errorLog:"客户端socket短连接失败",msg:msg);
      }

    }

  }

  //2.释放ok
  static void clean(){
    //
    try{
      _queue?.xRelease();
      //断开所有连接
      if(serverSocketAPI!=null){
        serverSocketAPI!.xRelease();
        serverSocketAPI=null;
      }

      //
      for(XClientSocketLongConnectAPI clientSocketAPI in _listClientSocketLongConnectAPI){
        clientSocketAPI.xRelease();
      }
      _listClientSocketLongConnectAPI.clear();

      //
      socketDeviceList.clear();
    }catch(e){
      XLogUtils.printLog('---socketUtils clean报错: $e');
    }

  }

  //3.添加设备记录和连接ok
  static void addDevice(XBaseDevice baseDevice){

    try{
      //
      if(!baseDevice.isServerSocket && XStringUtils.isEmpty(baseDevice.ip)){
        //客户端
        XLogUtils.printLog('---客户端IP值为空');
        return;
      }

      if(baseDevice.isServerSocket){
        //服务端,自动设置为自定义socket通讯
        baseDevice.isCustomSocketCommunication=true;
      }

      //1.保存连接设备记录
      if(!socketDeviceList.contains(baseDevice)){
        XLogUtils.printLog('---添加设备记录');
        socketDeviceList.add(baseDevice);
        //XLogUtils.printLog("---当前设备数:${connectedDeviceList.length}");
        String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
        XSharePreferencesUtils.saveString('$userGroup${XConstants.SP_SocketDevicesList}', XJsonUtils.obj2Json(socketDeviceList));

        //2.连接设备
        _connectDevice(baseDevice);
      }else{
        XLogUtils.printLog('---添加设备ip已存在');
      }

    }catch(e){
      XLogUtils.printLog('connectDevice报错: $e');
    }

  }

  //4.更新设备设置 ok
  static void updateDevice(XBaseDevice device){

    if(XStringUtils.isEmpty(device.ip)){
      XLogUtils.printLog('---设备IP为空');
      return;
    }

    for(XBaseDevice deviceItem in socketDeviceList){
      if(device==deviceItem){
        deviceItem.deviceName=device.deviceName;
        deviceItem.nickName=device.nickName;
        deviceItem.deviceKey=device.deviceKey;
        deviceItem.brand=device.brand;
        deviceItem.isConnected=device.isConnected;
        deviceItem.isUserSelect=device.isUserSelect;
        deviceItem.isEnable=device.isEnable;
        deviceItem.customType=device.customType;
        deviceItem.isServerSocket=device.isServerSocket;
        deviceItem.port=device.port;
        deviceItem.ip=device.ip;
        deviceItem.isGBK=device.isGBK;
        deviceItem.isSocketShortConnect=device.isSocketShortConnect;
        deviceItem.isCustomSocketCommunication=device.isCustomSocketCommunication;

        deviceItem.scenes =device.scenes;
        deviceItem.printerPagerSize=device.printerPagerSize;
        deviceItem.serialNumber=device.serialNumber;

        deviceItem.printCommandType=device.printCommandType;
        deviceItem.printTypeName=device.printTypeName;
        deviceItem.printerDPI=device.printerDPI;
        deviceItem.printerLabelSizeWidth=device.printerLabelSizeWidth;
        deviceItem.printerLabelSizeHeight=device.printerLabelSizeHeight;

        break;
      }
    }

    //更新保存
    String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
    XSharePreferencesUtils.saveString('$userGroup${XConstants.SP_SocketDevicesList}', XJsonUtils.obj2Json(socketDeviceList));

  }


  //5.1.移除设备并删除记录 ok
  static void removeDevice(XBaseDevice device){
    //断开连接
    if(device.isServerSocket){
      //服务端
      if(serverSocketAPI!=null){
        serverSocketAPI!.xRelease();
        serverSocketAPI=null;
      }

    }else{
      //客户端
      _listClientSocketLongConnectAPI.removeWhere((XClientSocketLongConnectAPI clientSocketAPI){
        if(device==clientSocketAPI.device){
          clientSocketAPI.xRelease();
          return true;
        }else{
          return false;
        }
      });
    }


    //2.移除设备记录
    socketDeviceList.remove(device);

    //更新保存
    String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
    XSharePreferencesUtils.saveString('$userGroup${XConstants.SP_SocketDevicesList}', XJsonUtils.obj2Json(socketDeviceList));

  }
  //5.2 删除服务端
  static void removeServerSocketDevice(){
    //1.断开和删除连接
    if(serverSocketAPI!=null){
      serverSocketAPI!.xRelease();
      serverSocketAPI=null;
    }

    //2.移除设备记录
    socketDeviceList.removeWhere((XBaseDevice device){
      if(device.isServerSocket){
        return true;
      }else{
        return false;
      }
    });

    //更新保存
    String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
    XSharePreferencesUtils.saveString('$userGroup${XConstants.SP_SocketDevicesList}', XJsonUtils.obj2Json(socketDeviceList));

  }
  //5.3 删除所有客户端
  static void removeAllClientSocketDevice(){
    //断开和删除连接, 客户端(适用多个)
    _listClientSocketLongConnectAPI.removeWhere((XClientSocketLongConnectAPI clientSocketAPI){
      clientSocketAPI.xRelease();
      return true;
    });

    //2.移除设备记录
    socketDeviceList.removeWhere((XBaseDevice device){
      if(!device.isServerSocket){
        return true;
      }else{
        return false;
      }
    });

    //更新保存
    String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
    XSharePreferencesUtils.saveString('$userGroup${XConstants.SP_SocketDevicesList}', XJsonUtils.obj2Json(socketDeviceList));

  }
  //5.4 删除客户端by customType
  static void removeClientSocketDeviceByType(String deviceCustomType){
    //断开和删除连接, 客户端(适用多个)
    _listClientSocketLongConnectAPI.removeWhere((XClientSocketLongConnectAPI clientSocketAPI){
      if(deviceCustomType==clientSocketAPI.device.customType){
        clientSocketAPI.xRelease();
        return true;
      }else{
        return false;
      }
    });

    //2.移除设备记录
    socketDeviceList.removeWhere((XBaseDevice device){
      if(!device.isServerSocket && deviceCustomType==device.customType){
        return true;
      }else{
        return false;
      }
    });

    //更新保存
    String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
    XSharePreferencesUtils.saveString('$userGroup${XConstants.SP_SocketDevicesList}', XJsonUtils.obj2Json(socketDeviceList));

  }

  //5.5 删除客户端by ip,port
  static void removeClientSocketDeviceByServerIP(String serverIP, int serverPort){
    //断开和删除连接, 客户端(适用多个)
    _listClientSocketLongConnectAPI.removeWhere((XClientSocketLongConnectAPI clientSocketAPI){
      if(serverIP==clientSocketAPI.device.ip && serverPort==clientSocketAPI.device.port){
        clientSocketAPI.xRelease();
        return true;
      }else{
        return false;
      }
    });

    //2.移除设备记录
    socketDeviceList.removeWhere((XBaseDevice device){
      if(!device.isServerSocket && serverIP==device.ip && serverPort==device.port){
        return true;
      }else{
        return false;
      }
    });

    //更新保存
    String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
    XSharePreferencesUtils.saveString('$userGroup${XConstants.SP_SocketDevicesList}', XJsonUtils.obj2Json(socketDeviceList));

  }

  //6.发送消息(添加到队列处理,适用多端打印)ok
  static void sendMsgToQueue(XBaseQueueMessage msg){
    try{
      _queue?.addNewMsgToQueueForWaitQueueAutoHandle(msg);
    }catch(e){
      XLogUtils.printLog('---sendMsgToQueue报错: $e');
    }
  }


  //7.添加各种监听
  //添加Socket设备连接状态监听
  static void addClientSocketDeviceConnectListener(XFunctionClientSocketDeviceConnectListener? listener){
    XSocketDeviceNotifyCallback.instance.addClientSocketDeviceConnectListener(listener);
  }
  static void addServerSocketDeviceConnectListener(XFunctionServerSocketListener? listener){
    XSocketDeviceNotifyCallback.instance.addServerSocketDeviceConnectListener(listener);
  }
  //删除Socket设备连接状态监听
  static void removeClientSocketDeviceConnectListener(XFunctionClientSocketDeviceConnectListener? listener){
    XSocketDeviceNotifyCallback.instance.removeClientSocketDeviceConnectListener(listener);
  }
  static void removeServerSocketDeviceConnectListener(XFunctionServerSocketListener? listener){
    XSocketDeviceNotifyCallback.instance.removeServerSocketDeviceConnectListener(listener);
  }

  //添加 写入内容到Socket设备状态监听
  static void addServerSocketDeviceWriteMessageListener(XFunctionWriteMessageToSocketDeviceListener? listener){
    XSocketDeviceNotifyCallback.instance.addServerSocketDeviceWriteMessageListener(listener);
  }
  static void addClientSocketDeviceWriteMessageListener(XFunctionWriteMessageToSocketDeviceListener? listener){
    XSocketDeviceNotifyCallback.instance.addClientSocketDeviceWriteMessageListener(listener);
  }
  //删除 写入内容到Socket设备状态监听
  static void removeServerSocketDeviceWriteMessageListener(XFunctionWriteMessageToSocketDeviceListener? listener){
    XSocketDeviceNotifyCallback.instance.removeServerSocketDeviceWriteMessageListener(listener);
  }
  static void removeClientSocketDeviceWriteMessageListener(XFunctionWriteMessageToSocketDeviceListener? listener){
    XSocketDeviceNotifyCallback.instance.removeClientSocketDeviceWriteMessageListener(listener);
  }

  //添加 接收Socket设备消息监听
  static void addServerSocketDeviceReceiveMessageListener(XFunctionReceiveSocketDeviceMessageListener? listener){
    XSocketDeviceNotifyCallback.instance.addServerSocketDeviceReceiveMessageListener(listener);
  }
  static void addClientSocketDeviceReceiveMessageListener(XFunctionReceiveSocketDeviceMessageListener? listener){
    XSocketDeviceNotifyCallback.instance.addClientSocketDeviceReceiveMessageListener(listener);
  }
  //删除 接收Socket设备消息监听
  static void removeServerSocketDeviceReceiveMessageListener(XFunctionReceiveSocketDeviceMessageListener? listener){
    XSocketDeviceNotifyCallback.instance.removeServerSocketDeviceReceiveMessageListener(listener);
  }
  static void removeClientSocketDeviceReceiveMessageListener(XFunctionReceiveSocketDeviceMessageListener? listener){
    XSocketDeviceNotifyCallback.instance.removeClientSocketDeviceReceiveMessageListener(listener);
  }

  ///////////////////////


  //连接设备ok
  static void _connectDevice(XBaseDevice baseDevice)
  {
    try{
      if(baseDevice.isServerSocket){
        //服务端socket
        if(serverSocketAPI!=null){
          serverSocketAPI!.xRelease();
          serverSocketAPI=null;
        }
        XLogUtils.printLog('---服务端socket设备正在连接中...');
        serverSocketAPI=XServerSocketAPI(baseDevice);
        serverSocketAPI!.start();
      }else{
        //客户端socket,长连接
        if(!baseDevice.isSocketShortConnect){
          //
          XClientSocketLongConnectAPI clientSocketAPI=XClientSocketLongConnectAPI(baseDevice);
          if(!_listClientSocketLongConnectAPI.contains(clientSocketAPI)){
            XLogUtils.printLog('---客户端socket(长连接)设备正在连接中...');
            clientSocketAPI.connect();
            _listClientSocketLongConnectAPI.add(clientSocketAPI);
          }
        }
      }

    }catch(e){
      XLogUtils.printLog('connectSocketDevice报错: $e');
    }

  }


  //处理写入消息成功 ok
  static void _handleWriteSocketDeviceSucceed(
      {
        required bool isServer,
        required bool isCustomSocketCommunication,
        required String ip,
        required XBaseQueueMessage msg,
      }
      )
  {

    //1.通知队列处理成功信息
    _queue?.handleSucceedMessageAndUnLockTempMessageQueue(msg.msgId);

    //心跳包内部处理,不用发通知,非自定义socket通讯(客户端发送消息,不需要服务端回调确认发送成功), 本地打印消息,通知外界
    if(!msg.isHeartbeatCommand && (isServer || !isCustomSocketCommunication)){
      //
      XLogUtils.printLog("---socket msg写入成功: isServerSocket= $isServer, ip= $ip, msgId=${msg.msgId}");
      //
      XSocketDeviceNotifyCallback.instance.writeMsgToSocketDeviceCallback(
        isSuccess:true,
        isServer:isServer,
        ip:ip,
        msg:msg,
      );
    }

  }

  //处理写入消息失败 ok
  static void _handleWriteSocketDeviceFailed(
      {
        required bool isServer,
        required String ip,
        required String errorLog,
        required XBaseQueueMessage msg
      }
      )
  {

    //1.通知队列处理失败信息
    _queue?.handleFailedMessageAndUnlockTempMessageQueue(msg.msgId,errorLog);

    //2.//心跳包内部处理,不用发通知
    if (!msg.isHeartbeatCommand){
      XLogUtils.printLog('---socket msg写入失败: isServerSocket= $isServer, ip= $ip,msgId=${msg.msgId}, errorLog=$errorLog');

      //本地socket消息,通知外界
      XSocketDeviceNotifyCallback.instance.writeMsgToSocketDeviceCallback(
        isServer:isServer,
        isSuccess:false,
        ip:ip,
        msg:msg,
      );
    }else{
      XLogUtils.printLog('---心跳数据写入失败: isServerSocket= $isServer, ip= $ip, errorLog=$errorLog',tag: 'XOther');
    }
  }

}